package org.example.authservice.utils;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

/**
 * @author 周昊
 * @version 1.0
 * @since 2024/12/20 21:12
 */
@Slf4j
public class AESUtil {

    // AES秘钥
    private static final String KEY = "5JKRGV0QO4WK1WCWVK55YEU0A1NPOXOP";

    private AESUtil() {}

    /**
     * AES加密
     */
    public static String encrypt(Object content) {

        String data;

        if (null == content) {
            return null;
        }

        // 判断content是否为字符串
        if (content instanceof String) {
            data = content.toString();
        } else {
            data = JSON.toJSONString(content);
        }

        // 将加密过的byte[]数据转换成Base64编码字符串
        return base64ToString(aesECBEncrypt(data.getBytes(StandardCharsets.UTF_8), KEY.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * AES解密
     */
    public static Object decrypt(String content) {

        if (null == content) {
            return null;
        }

        try {
            byte[] base64 = stringToBase64(content);
            byte[] bytes = aesECBDecrypt(base64, KEY.getBytes(StandardCharsets.UTF_8));
            String result = new String(bytes, StandardCharsets.UTF_8);
            String data = result.replaceAll("\"", "");

            // 判断解密出来的数据是字符串还是json
            if (data.startsWith("{") && data.endsWith("}")) {
                return JSON.parse(data);
            } else {
                return data;
            }

        } catch (Exception e) {
            log.error("AESUtil.decrypt() error, {}", e.getMessage(), e);
        }

        return null;
    }

    private static byte[] aesECBEncrypt(byte[] content, byte[] keyBytes) {

        try {
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(content);
        } catch (Exception e) {
            log.error("AESUtil.aesECBEncrypt() error, {}", e.getMessage(), e);
        }

        return null;
    }

    private static byte[] aesECBDecrypt(byte[] content, byte[] keyBytes) {

        try {
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(content);
        } catch (Exception e) {
            log.error("AESUtil.aesECBDecrypt() error, {}", e.getMessage(), e);
        }

        return null;
    }

    /**
     * 将字符串转换成Base64
     */
    public static byte[] stringToBase64(String key) {
        return Base64.getDecoder().decode(key);
    }

    /**
     * 将Base64转换成字符串
     */
    public static String base64ToString(byte[] key){
        return Base64.getEncoder().encodeToString(key);
    }

}